<?php
namespace lib;

class DB {
	
	static public $instance = FALSE;

	//数据库链接句柄
	private $db = FALSE;

	private $table = '';
	private $fields = '*';
	private $where = '';
	private $limit = '';

	private $config = FALSE;

	/**
	 * 获取单例
	 * @param  string $configFile [数据库配置文件]
	 * @return            
	 */
	static public function instance($configFile = '')
	{
		if ( !self::$instance ) 
		{
			self::$instance = new self($configFile);
		}

		return self::$instance;
	}

	
	private function __construct($configFile='')
	{
		$this->config = config('database');
		if ( $configFile ) 
		{
			$this->config = array_merge($this->config, config('database/' . $configFile));
		}

		$this->connet();

	}

	/**
	 * 链接数据库
	 * @return
	 */
	private function connet()
	{
		if ( empty($this->config) ) 
		{
			die('未获取到数据库配置文件');
		}

		$c = $this->config;

		$this->db = new \mysqli( $c['host'] , $c['user'], $c['pass'], $c['database'] , $c['port'] ? $c['port'] : '3306');

		if ( mysqli_connect_errno() ) 
		{
			die(mysqli_connect_error());
		}

		$this->db->query('set names ' . $c['charset']);

	}

	/**
	 * 指定操作的数据表
	 * @param  $tableName 
	 * @return           
	 */
	public function table($tableName)
	{	
		$this->table = $this->config['table_prefix'] . $tableName;
		$this->table = "`{$this->table}`";
		return $this;
	}
	/**
	 * 指定操作的数据表
	 * @param  $tableName 
	 * @return           
	 */
	public function fields($fields)
	{	
		$this->fields = $fields ? $fields : '*';
		return $this;
	}
	/**
	 * where条件
	 * @param  $where 
	 */
	public function where($where)
	{
		if ( is_string($where) )
		{
			$this->where = ' WHERE ' . $where;
		}
		return $this;
	}
	/**
	 * limit
	 * @param  $where 
	 */
	public function limit($offset, $limit=0)
	{
		if ( $offset && $limit )
		{
			$this->limit = "limit {$offset},{$limit}";
		}
		elseif ( $offset )
		{
			$this->limit = "limit {$offset}";
		}
		return $this;
	}
	/**
	 * 添加记录集
	 * @param  $data
	 * @return      
	 */
	public function insert($data)
	{
		if ( empty($data) || !is_array($data)) return false;
		if ( !$this->table ) return false;
		$sql = "INSERT INTO {$this->table} #fields# VALUES #values#";
		$fields = '(';
		$values = '(';
		foreach ($data as $field => $v) 
		{
			$fields .= "`{$field}`,";
			$values .= !is_string($v) ? "{$v}," : "'{$v}',";
		}
		$fields = trim($fields, ',') . ')';
		$values = trim($values, ',') . ')';
		$sql = str_replace('#fields#', $fields, $sql);
		$sql = str_replace('#values#', $values, $sql);
		$this->lasSql = $sql;
		$result = $this->db->query($sql);
		if ( !$result ) 
		{
			printf("Error: %s\n", $this->db->error);die;
		}
		return $this->db->insert_id;
	}
	/**
	 * 更新记录集
	 * @param $data 更新的数据
	 */
	public function update($data)
	{
		if ( empty($data) || !is_array($data)) return false;
		if ( !$this->table ) return false;
		$sql = "UPDATE {$this->table} SET #fields# {$this->where}";

		$fields = '';
		foreach ($data as $field => $value) {
			$fields .= ("`{$field}` = " . (is_string($value) ? "'{$value}'" : $value) . ',');
		}
		if ( !$fields ) return false;
		$sql = str_replace('#fields#', trim($fields, ','), $sql);
		
		$result = $this->db->query($sql);
		if ( !$result )
		{
			printf("Error: %s\n", $this->db->error);die;
		}

		return $this->db->affected_rows;
	}
	/**
	 * 查询记录集
	 * @return  array,多维数组
	 */
	public function fetchAll()
	{
		if ( !$this->table ) return false;

		$sql = "SELECT {$this->fields} FROM {$this->table} {$this->where} {$this->limit}";
		$this->lasSql = $sql;
		$result = $this->db->query($sql);
		if ( !$result )
		{
			printf("Error: %s\n", $this->db->error);die;
		}
		$rows = [];
		while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
			$rows[] = $row;
		}
		$result->close();
		return $rows;
	}
	/**
	 * 获取单条记录集
	 * @return array 一维数组
	 */
	public function fetch()
	{
		$fetch = $this->limit(1)->fetchAll();
		return empty($fetch) ? [] : $fetch[0];
	}

	/**
	 * 用作与调用数据库原始方法 
	 * @param  $name  
	 * @param  $params
	 * @return        
	 */
	public function __call($name, $params)
	{
		if (in_array($name, ['query']) && method_exists($this->db, $name)) 
		{
			return call_user_func_array(array($this->db, $name), $params);
		}

	}

	

}
